<template>
  <div class="layeredGraph-content">
    <el-row :gutter="20">
      <el-col :span="4" class="layeredGraph-left">
        <div class="layeredGraph-title">选择单位</div>
        <el-form :inline="true" ref="formInline" :model="formInline" @submit.native.prevent>
          <el-form-item style="width: 100%;">
            <el-select filterable style="width: 100%;" v-model="formInline.organizationId" @change="changeUnit()">
              <el-option
                v-for="item in orgList"
                :key="item.organizationId"
                :label="item.shortName"
                :value="item.organizationId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="layeredGraph-title">调节图标大小（ {{ iconSize }}%）</div>
        <div class="block slider-padding">
          <el-slider v-model="iconSize" @change="changeSize"></el-slider>
        </div>
        <!-- <div class="layeredGraph-title">类型筛选</div>
        <div class="block slider-padding"></div>-->
        <div class="layeredGraph-title">建筑物结构</div>
        <el-input placeholder="输入关键字搜索" v-model="filterText"></el-input>
        <el-tree
          ref="tree"
          class="filter-tree"
          v-loading="tree.loading"
          node-key="id"
          :data="tree.data"
          :props="tree.defaultProps"
          default-expand-all
          :filter-node-method="filterNode"
          :highlight-current="true"
          :expand-on-click-node="false"
          @node-click="changeLevel"
        ></el-tree>
      </el-col>
      <el-col :span="(!isEdit?20:17)" class="layeredGraph-right">
        <div class="layeredGraph-title">
          {{ msg }}
          <i v-if="!isEdit" class="el-icon-rank" @click="scaleLayer()"></i>
          <i v-else class="el-icon-upload2" @click="uploadLayer()"></i>
        </div>
        <div class="fencengtu-pic-parent" @click="() => {markValue != '' ? isFullscreen = true : isFullscreen = false}">
          <div
            class="fencengtu-pic"
            :model="layerPic"
            :style="{
                          backgroundImage: 'url(' + layerPic + ')', 
                          backgroundSize:'100% 100%',
                          backgroundRepeat:'no-repeat'
                      }"
          >
            <el-popover
              v-for="item in markTable.data"
              :key="item.xAxis"
              placement="top-start"
              trigger="hover"
              :visible-arrow="false"
              :title="item.markersName"
            >
              <div v-for="i in item.rtObjs" class="text item" :key="i.rtObjName">
                <div v-if="i.rtTypeId == 1">物联设备-{{ i.rtObjName }}</div>
                <div v-if="i.rtTypeId == 2">资产-{{ i.rtObjName }}</div>
                <div v-if="i.rtTypeId == 3">视频-{{ i.rtObjName }}</div>
                <div v-if="i.rtTypeId == 4">巡检点位-{{ i.rtObjName }}</div>
              </div>
              <img
                slot="reference"
                v-if="item.iconUrl"
                :src="item.iconUrl"
                :style="{
                              display: 'block',
                              width:( smallLayer.markerW * smallLayer.zoomPercent ) +'px',
                              height:( smallLayer.markerH * smallLayer.zoomPercent ) +'px',
                              position:'absolute',
                              left:item.xAxis + '%',
                              top:item.yAxis + '%',
                              cursor:'pointer',
                              marginTop:'-' + ( smallLayer.markerW * smallLayer.zoomPercent )/2 + 'px',
                              marginLeft:'-' + ( smallLayer.markerW * smallLayer.zoomPercent )/2 + 'px',
                              borderRadius:( smallLayer.markerW * smallLayer.zoomPercent )/2 + 'px',
                              zIndex:2
                            }"
              />
            </el-popover>
            <div v-for="item in markTable.data" :key="item.yAxis">
              <img
                v-if="item.alarmIcon"
                :src="item.alarmIcon"
                :style="{
                                width:( smallLayer.markerAlarmW * smallLayer.zoomPercent ) +'px',
                                height:( smallLayer.markerAlarmH * smallLayer.zoomPercent ) +'px',
                                position:'absolute',
                                left:item.xAxis + '%',
                                top:item.yAxis + '%',
                                cursor:'pointer',
                                marginTop:'-' + ( smallLayer.markerAlarmW * smallLayer.zoomPercent )/2 + 'px',
                                marginLeft:'-' + ( smallLayer.markerAlarmW * smallLayer.zoomPercent )/2 + 'px',
                                borderRadius:( smallLayer.markerAlarmW * smallLayer.zoomPercent )/2 + 'px',
                                zIndex:1
                            }"
              />
            </div>
          </div>
        </div>
        <div v-show="isEdit">
          <div class="layeredGraph-title">标注列表</div>
          <el-table v-loading="markTable.Loading" :data="markTable.data" ref="maintenceTableData" style="width: 100%">
            <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
            <el-table-column prop="markersName" label="名称"></el-table-column>
            <el-table-column label="关联物联设备">
              <template slot-scope="props">
                <span v-for="item in props.row.rtObjs" :key="item.rtObjId">{{ item.rtObjName }} ,</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="props">
                <!-- <el-button type="text" size="small" @click="">定位</el-button> -->
                <el-button type="text" size="small" @click="deleteMarkFn(props.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            @size-change="sizeChange"
            @current-change="pageChange"
            :current-page="markTable.pageIndex"
            :page-sizes="[5, 10, 50, 100]"
            :page-size="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="markTable.pageTotal"
          ></el-pagination>
        </div>
      </el-col>
      <el-col v-show="isEdit" :span="3" class="layeredGraph-right-right">
        <div class="layeredGraph-title">打点类型</div>
        <el-collapse>
          <el-collapse-item v-for="item in markTools" :title="item.title" :key="item.title">
            <el-radio
              class="mark-tool"
              v-for="i in item.node"
              v-model="markValue"
              :key="i.id"
              :label="i.id"
              :icon="i.icon"
              :rtTypeId="item.rtTypeId"
              @change="changeIcon(i.id,i.icon,i.name,item.rtTypeId)"
            >{{ i.name }}</el-radio>
          </el-collapse-item>
        </el-collapse>
        <div class="layeredGraph-title">关联物联设备</div>
        <el-select
          multiple
          v-model="relateFcIds"
          placeholder="请选择关联物联设备"
          filterable
          :filter-method="getFcfSelectList"
          :loading="layerLoading"
          id="layerRelateFcIds"
        >
          <el-option v-for="item in layerFcOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="layerIndex"
            small
            layout="total, prev, pager, next"
            :total="layerTotal"
          ></el-pagination>
        </el-select>
        <!-- <div class="layeredGraph-title">关联资产</div>
            <el-select multiple v-model="assetIds" 
                placeholder="请选择关联资产"
                filterable 
                :filter-method="getAssetSelectList"
                :loading="assetLoading"
                id="layerAsset">
                <el-option
                v-for="item in assetFcOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
                </el-option>
                <el-pagination
                @current-change="handleCurrentChange_asset"
                :current-page.sync="assetIndex"
                small
                layout="total, prev, pager, next"
                :total="assetTotal">
                </el-pagination>
        </el-select>-->
        <el-button type="primary" style="float: right;margin-top: 10px;" @click="quitSaveMark()">保存</el-button>
      </el-col>
      <!-- 全屏容器 -->
      <el-dialog
        :close-on-click-modal="false"
        class="layer-full-screen"
        title
        :visible.sync="isFullscreen"
        :width="screenW"
        :height="screenH"
        :style="{
              width:screenW, 
              height:screenH,
          }"
      >
        <large-layer-contain
          :markData="markTable.data"
          :layerPic="layerPic"
          :buildId="buildId"
          :iconSize="iconSize"
          :isFullscreen="isFullscreen"
          :markIcon="markIcon"
          :markCallBack="markCallBack"
        ></large-layer-contain>
      </el-dialog>
      <!-- 上传分层图 -->
      <el-dialog :close-on-click-modal="false" title="上传分层图" :visible.sync="isUpload" width="600px">
        <up-load-layer :callBackUrl="callBackUrl"></up-load-layer>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import util from '@/utils/util'
import { getDictByCode } from '@/api/dic'
import screenfull from 'screenfull'
import LargeLayerContain from './compts/LargeLayerContain'
import UpLoadLayer from './compts/UpLoadLayer'
import { getOrgList } from '@/api/org'
import { getAListForPc } from '@/api/assets'
import { getFbsTree } from '@/api/sysConfig'
import {
  updateFbsIconPercent,
  getFbsIconPercent,
  getCategoryListByOrgId,
  updateMarkersExt,
  updateFbsLayered,
  getPicturesLayeredList,
  delMarkers,
  getFcfSelectList,
} from '@/api/layeredGraph'

export default {
  name: 'LayeredGraph',
  components: {
    LargeLayerContain,
    UpLoadLayer,
  },
  data() {
    return {
      msg: '分层图',
      isEdit: true,
      layerPic: '',
      currentTreeData: [],
      /*预览页面接收参数*/
      formInline: {
        organizationId: '',
      },
      buildId: 0,
      /*业主单位*/
      orgList: [],
      iconSize: 100,
      isFullscreen: false,
      screenW: window.screen.width + 'px',
      screenH: window.screen.height + 'px',
      markTools: [],
      markIcon: '',
      markIconName: '',
      markValue: '',
      rtChildTypeId: 0,
      addNewMark: [],
      saveNewFlag: 0,
      /*关联设备*/
      layerLoading: false,
      relateFcIds: [],
      layerFcOptions: [], // 关联物联设备
      layerIndex: 1,
      layerTotal: 0,
      /*关联资产*/
      assetLoading: false,
      assetIds: [],
      assetFcOptions: [], // 关联物联设备
      assetIndex: 1,
      assetTotal: 0,
      /*上传图片*/
      isUpload: false,
      newLayerUrl: '',
      /*列表*/
      markTable: {
        loading: false,
        data: [],
        pageIndex: 1,
        pageSize: 5,
        pageTotal: 0,
      },
      isDelete: 0,
      filterText: '',
      tree: {
        loading: false,
        data: [],
        defaultProps: {
          children: 'nodes',
          label: 'text',
          value: 'id',
        },
      },
      smallLayer: {
        zoomPercent: 1,
        markerW: 32,
        markerH: 32,
        markerAlarmW: 40,
        markerAlarmH: 40,
      },
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
  },
  created() {
    let self = this
    self.bindOwnerUnit()
  },
  mounted() {
    window.onresize = () => {
      // 全屏下监控是否按键了ESC
      if (!util.checkFull()) {
        // 全屏下按键esc后要执行的动作
        this.isFullscreen = false
        // this.markValue = '';
      }
    }
  },
  methods: {
    //业主单位
    bindOwnerUnit: function () {
      let self = this
      getOrgList({ queryType: 0 }).then((data) => {
        if (data.data.length > 0) {
          self.formInline.organizationId = data.data[0].organizationId
          self.changeUnit()
        }
        self.orgList = data.data
      })
    },
    //切换联网单位
    changeUnit() {
      this.msg = '分层图'
      this.filterText = ''
      this.layerPic = ''
      this.markValue = ''
      this.assetIds = []
      this.relateFcIds = []
      this.markTable.data = []
      this.markTools = []
      this.getTreeData()
      this.getMarkTools()
      this.getFcfSelectList()
      this.getAssetSelectList()
    },
    //建筑物树
    getTreeData() {
      let self = this
      self.tree.loading = true
      getFbsTree({
        organizationId: self.formInline.organizationId,
        buildId: 0,
      }).then((data) => {
        if (data.status == 200) {
          self.tree.data = data.data
        }
        self.tree.loading = false
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.text.indexOf(value) !== -1
    },
    //切换楼层
    changeLevel(value) {
      let self = this
      self.buildId = value.id
      self.msg = value.text
      if (value.isAddLayeredGraph == 1 && value.layeredGraphUrl != '') {
        self.getDefauleIconSize()
        self.layerPic = value.layeredGraphUrl
        self.currentTreeData = value
      } else {
        self.layerPic = ''
        self.currentTreeData = []
        self.$message({
          message: '该层暂无分层图',
          type: 'warning',
        })
      }
      if (self.isEdit) {
        self.markValue = ''
        self.assetIds = []
        self.relateFcIds = []
        self.markTable.pageIndex = 1
        self.getMarkList()
        self.getFcfSelectList('')
      }
    },
    //切换滑杆
    changeSize(value) {
      let self = this
      if (self.buildId != 0) {
        updateFbsIconPercent({
          id: self.buildId,
          iconPercent: value,
          account: this.$store.state.userinfo.accountName,
        }).then((data) => {
          self.smallLayer.zoomPercent = self.iconSize / 100
        })
      } else {
        self.$message({
          message: '调节无效，请选择楼层',
          type: 'warning',
        })
      }
    },
    //获取指定消防建筑物图标大小
    getDefauleIconSize() {
      let self = this
      getFbsIconPercent({
        id: self.buildId,
      }).then((data) => {
        self.iconSize = data.data
        self.smallLayer.zoomPercent = self.iconSize / 100
      })
    },
    //全屏
    scaleLayer() {
      let self = this
      if (self.layerPic) {
        if (!screenfull.enabled) {
          self.$message({
            message: 'Your browser does not work',
            type: 'warning',
          })
          return false
        }
        self.isFullscreen = true
        screenfull.toggle()
      } else {
        this.$message({
          message: '暂无分层图',
          type: 'warning',
        })
      }
    },
    //获取图标
    getMarkTools() {
      // this.markTools = [
      //   {
      //     "rtTypeId":4,
      //     "title":"巡检点位",
      //     "node":[{
      //         "id":4,
      //         "name":"点位",
      //         "icon":"resource/rdspFile_1556529161167.png"
      //     }]
      //   }
      // ];
      //获取物联设备图标
      getCategoryListByOrgId({
        organizationId: this.formInline.organizationId,
      }).then((data) => {
        if (data.data && data.data.length > 0) {
          let obj3 = {}
          obj3.title = '物联设备'
          obj3.rtTypeId = 1
          obj3.node = []
          let arr = data.data
          for (let n in arr) {
            let obj4 = {}
            obj4.id = arr[n].id
            obj4.name = arr[n].name
            obj4.name = arr[n].name
            obj4.icon = JSON.parse(arr[n].icon).icon
            obj3.node.push(obj4)
          }
          this.markTools.push(obj3)
        }
      })
      // getDictByCode({code: 54}).then((data)=>{
      //     if(data.data){
      //       let re = data.data;
      //       let obj1 = {};
      //       obj1.title = re.name;
      //       obj1.rtTypeId = 3;
      //       obj1.node = [];
      //       if(re.dictValueObj.length > 0){
      //           for(let i in re.dictValueObj){
      //               if(re.dictValueObj[i].dictValue){
      //                   obj1.node.push(JSON.parse(re.dictValueObj[i].dictValue));
      //               }
      //           }
      //       }
      //       this.markTools.push(obj1);
      //     }
      // });
    },
    //选择图标
    changeIcon(id, icon, name, rtTypeId) {
      //过滤页面新标注点
      let oldArr = this.markTable.data.filter((o) => o.id != 0)
      this.markTable.data = oldArr
      if (this.layerPic) {
        this.rtTypeId = rtTypeId
        this.markValue = id
        this.markIcon = icon
        this.markIconName = name
        this.scaleLayer()
      } else {
        this.$message({
          message: '暂无分层图',
          type: 'warning',
        })
      }
      // 清空关联物联设备
      this.relateFcIds = []
      this.getFcfSelectList('')
    },
    //大图标点之后的回调
    markCallBack(newArr) {
      //过滤出ID为0的对象
      let arr = newArr.filter((o) => o.id == 0)
      this.addNewMark = arr
      //大图标点之后
      if (newArr.length > 0) {
        this.markTable.data = newArr
      }
    },
    /*获取关联物联设备*/
    getFcfSelectList(name, pageChange) {
      let self = this
      // 重新搜索时页码复原
      if (!pageChange) {
        this.layerIndex = 1
      }
      let parames = {
        fbsId: self.buildId || 0,
        fcfTypeId: self.markValue || 0,
        organizationId: self.formInline.organizationId,
        parentId: 0,
        pageIndex: self.layerIndex - 1,
        pageSize: 10,
        name: name || '',
      }
      self.layerLoading = true
      getFcfSelectList(parames).then((data) => {
        self.layerFcOptions = data.data
        self.layerTotal = data.total
        self.layerLoading = false
      })
    },
    handleCurrentChange(currentpage) {
      this.layerIndex = currentpage
      this.getFcfSelectList(
        $('#layerRelateFcIds .el-select__input').val(),
        true
      )
    },
    handleCurrentChange_asset(currentpage) {
      this.assetIndex = currentpage
      this.getAssetSelectList($('#layerAsset .el-select__input').val(), true)
    },
    /*资产*/
    getAssetSelectList(name, pageChange) {
      let self = this
      self.assetLoading = true
      // 重新搜索时页码复原
      if (!pageChange) {
        this.assetIndex = 1
      }
      getAListForPc({
        queryType: 1,
        organizationId: self.formInline.organizationId,
        name: name || '',
        categoryIds: '',
        fbsIds: '',
        isUse: -1,
        pageSize: 10,
        pageIndex: self.assetIndex - 1,
      }).then((data) => {
        if (data.status === 200) {
          self.assetFcOptions = data.data
          self.assetTotal = data.total
        }
        self.assetLoading = false
      })
    },
    /*验证保存*/
    quitSaveMark() {
      let self = this
      if (self.addNewMark.length > 0) {
        if (self.relateFcIds.length > 0) {
          self.save()
        } else {
          this.$message({
            message: '请关联物联网设备',
            type: 'warning',
          })
        }
      } else {
        this.$message({
          message: '尚未标点',
          type: 'warning',
        })
      }
    },
    /*保存*/
    //rtTypeId 关联对象类型 1：物联设备 2：资产 3:视频 4:巡检点位
    //rtObjId  关联对象编码id
    save() {
      let self = this
      let rtObjsArr = []
      $.each(self.relateFcIds, function (i) {
        rtObjsArr.push({
          rtTypeId: self.rtTypeId,
          rtObjId: self.relateFcIds[i],
          rtChildTypeId: self.markValue,
        })
      })
      $.each(self.assetIds, function (i) {
        rtObjsArr.push({
          rtTypeId: 2,
          rtObjId: self.assetIds[i],
        })
      })
      self.saveNewFlag = 0
      let param = {
        id: 0,
        markersName: self.markIconName,
        iconUrl: self.addNewMark[0].iconUrl,
        xAxis: self.addNewMark[0].xAxis,
        yAxis: self.addNewMark[0].yAxis,
        fireBuildingStructureId: self.buildId,
        rtObjs: JSON.stringify(rtObjsArr),
      }
      updateMarkersExt(param).then((data) => {
        this.$message({ message: '标注成功', type: 'success' })
        self.getMarkList()
        self.saveNewFlag = 1
        self.relateFcIds = ''
        self.assetIds = ''
      })
    },
    /*上传图片*/
    uploadLayer() {
      if (this.buildId != 0) {
        this.isUpload = true
      } else {
        this.$message({ message: '请选择建筑物', type: 'warning' })
      }
    },
    callBackUrl(url) {
      this.newLayerUrl = url
      updateFbsLayered({
        id: this.buildId,
        layeredGraphUrl: this.newLayerUrl,
      }).then((data) => {
        this.$message({ message: '上传成功', type: 'success' })
        this.layerPic = this.newLayerUrl
        this.isUpload = false
        this.getTreeData()
      })
    },
    /*获取列表*/
    getMarkList() {
      let self = this
      self.markTable.data = []
      if (self.buildId != 0) {
        self.markTable.loading = true
        getPicturesLayeredList({
          fbsId: self.buildId,
          type: 0,
          queryType: 1,
          pageIndex: self.markTable.pageIndex - 1,
          pageSize: self.markTable.pageSize,
          rtTypeIds: '1,2,3,4',
          markersName: '',
        }).then((data) => {
          if (data.status == 200) {
            self.markTable.data = data.data
            self.markTable.pageTotal = data.total
            self.markTable.loading = false
          }
        })
      }
    },
    //页码切换
    sizeChange(val) {
      this.markTable.pageIndex = 1
      this.markTable.pageSize = val
      this.getMarkList()
    },
    //翻页
    pageChange(val) {
      this.markTable.pageIndex = val
      this.getMarkList()
    },
    //删除标注点
    deleteMarkFn(row) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      that.isDelete = 0
      if (row) {
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          roundButton: true,
        })
          .then(() => {
            if (row.id == 0) {
              //过滤页面新标注点
              let oldArr = this.markTable.data.filter((o) => o.id != 0)
              this.markTable.data = oldArr
            } else {
              delMarkers({ id: row.id }).then((res) => {
                if (res.status === 200) {
                  this.$message({ message: '删除成功', type: 'success' })
                  that.isDelete = 1
                  that.getMarkList()
                } else {
                  that.$message.error(res.info)
                }
              })
            }
            // 阻止事件冒泡
            event.stopPropagation()
          })
          .catch(() => {})
      }
    },
  },
}
</script>
<style lang="less">
.fencengtu-pic-parent {
  width: 100%;
  position: relative;
  height: 0;
  padding-bottom: 56.25%;
  .fencengtu-pic {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
  }
}
.layeredGraph-content {
  position: relative;
  .layeredGraph-right {
    padding: 0 15px;
  }
  .layeredGraph-title {
    font-weight: bold;
    padding: 10px;
    background-color: #f7f7f7;
  }
  .slider-padding {
    padding: 10px 5px;
  }
  .el-form-item__content {
    width: 100%;
    margin-left: auto !important;
  }
  .el-icon-rank,
  .el-icon-upload2 {
    float: right;
    font-size: 20px;
    cursor: pointer;
  }
  .layer-full-screen {
    .el-dialog {
      width: 100%;
      height: 100%;
      margin-top: 0 !important;
    }
    .el-dialog__body {
      width: 100%;
      height: 100%;
      padding: 0;
    }
    .el-dialog__header {
      display: none;
    }
  }
  .mark-tool {
    width: 100%;
    margin-bottom: 10px;
  }
  .el-collapse-item__header {
    padding-left: 5px;
  }
}
</style>
